package com.bdqn.jpayhymeleaf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bdqn.jpayhymeleaf.entity.Role;
import com.bdqn.jpayhymeleaf.entity.User;
import com.bdqn.jpayhymeleaf.mapper.UserMapper;
import com.bdqn.jpayhymeleaf.repository.UserRepository;
import com.bdqn.jpayhymeleaf.service.IUserService;
import jakarta.annotation.Resource;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @version 2024-09-20
 * @Author:T369曹任柱
 */
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserRepository userRepository;
    @Resource
    private UserMapper userMapper;
    @Override
    public User login(String usrName, String usrPassword) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("usr_name",usrName);
        qw.eq("usr_password",usrPassword);
        return userMapper.selectOne(qw);
    }

    @Override
    public void saveUser(User user) {
        userMapper.updateById(user);
    }

    @Override
    public void deleteUser(Long usrId) {
        userMapper.deleteById(usrId);
    }

    @Override
    public User getUser(Long usrId) {
        return userMapper.selectById(usrId);
    }

    @Override
    public Page<User> findUsers(String usrName, Integer roleId, Pageable pageable) {
        Specification<User> specification=new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates=new ArrayList<>();
                if (usrName!=null && !usrName.equals("")){
                    predicates.add(criteriaBuilder.like(root.get("usrName"),"%"+usrName+"%"));
                }
                if (roleId!=null && roleId.longValue()!=01){
                    Role role=new Role();
                    role.setRoleId(roleId);
                    predicates.add(criteriaBuilder.equal(root.get("role"),role));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return userRepository.findAll(specification,pageable);
    }
}
